package com.wy2cloud.gateway.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.wy2cloud.core.tools.StringTools;
import com.wy2cloud.core.web.CookieTools;
import com.wy2cloud.jjwt.JsonWebTokenProperties;
import com.wy2cloud.jjwt.JsonWebTokenUtil;
import com.wy2cloud.jjwt.security.SecurityUserFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@SuppressWarnings("SpringJavaAutowiringInspection")
@Component
public class SecurityAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
	private JsonWebTokenUtil jsonWebTokenUtil;



    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain chain) throws ServletException, IOException {
    	
       // String authHeader = request.getHeader(jsonWebTokenUtil.getTokenHeader());
        //String tokenHead=jsonWebTokenUtil.getTokenHead();
        String authToken=jsonWebTokenUtil.getAuthToken(request);
        
        if (!StringTools.isEmpty(authToken)) {
            //String authToken = authHeader.substring(tokenHead.length()); // The part after "Bearer "
            String username = jsonWebTokenUtil.getUsernameFromToken(authToken);
            Map<String,Object> tokenMap=jsonWebTokenUtil.getMapFromToken(authToken);
            logger.info("checking authentication " + username);

            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                // 如果我们足够相信token中的数据，也就是我们足够相信签名token的secret的机制足够好
                // 这种情况下，我们可以不用再查询数据库，而直接采用token中的数据
                // 本例中，我们还是通过Spring Security的 @UserDetailsService 进行了数据查询
                // 但简单验证的话，你可以采用直接验证token是否合法来避免昂贵的数据查询
                //UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            	
            	UserDetails userDetails=SecurityUserFactory.generator((String)tokenMap.get("userId"), username, "", null,null);

                if (jsonWebTokenUtil.validateToken(authToken)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                            request));
                    logger.info("authenticated user " + username + ", setting security context");
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }

        chain.doFilter(request, response);
    }
    
    
}